package pers.cz.postgirl.core.async;

import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import pers.cz.jefconfig.config.JefConfiguration;
import pers.cz.postgirl.config.SystemEnum;
import pers.cz.postgirl.util.JefLog;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @program: postgirl-client
 * @description: 队列工具
 * @author: Cheng Zhi
 * @create: 2023-06-05 09:50
 **/
public class SpyDisruptorUtil {

    private static JefLog jefLog = new JefLog(SpyDisruptorUtil.class);

    /**
     * 注意bufferSize必须是2的幂
     */
    private static int ringBufferSize = JefConfiguration.getInt(SystemEnum.CLIENT_LOCALQUEUE_SIZE, 512);

    private static RingBuffer ringBuffer;

    public static RingBuffer getRingBuffer() {
        if (ringBuffer == null) {
            initDisruptor();
        }

        return ringBuffer;
    }

    public static void initDisruptor() {
        jefLog.debug("初始化队列长度为：" + ringBufferSize);
        ThreadPoolExecutor executor = DisruptorThreadPool.getExecutor();
        Disruptor<SpyEvent> disruptor = new Disruptor(new SpyHandlerEventFactory(), ringBufferSize, executor, ProducerType.MULTI, new BlockingWaitStrategy());
        disruptor.handleEventsWith(new SpyEventConsumer());
        disruptor.start();
        ringBuffer = disruptor.getRingBuffer();
    }
}
